package org.zhxy.core.principal.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zhxy.common.config.MapperFactory;
import org.zhxy.common.response.PageResult;
import org.zhxy.common.response.Result;
import org.zhxy.common.utils.Constants;
import org.zhxy.entity.system.Dictionary;

import java.util.List;
import java.util.Map;

@Service
@Transactional
public class DictionaryService {


    public PageResult<Dictionary> getList(Map<String, Object> map) {
        Integer page = Integer.parseInt(map.get(Constants.Blanket.PAGE).toString());
        Integer size = Integer.parseInt(map.get(Constants.Blanket.SIZE).toString());
        IPage<Dictionary> iPage = new Page<>(page,size);
        QueryWrapper<Dictionary> queryWrapper = new QueryWrapper<>();
        if(map.get(Constants.DB.NAME) != null && !map.get(Constants.DB.NAME).equals("")){
            queryWrapper.like(Constants.DB.NAME,map.get(Constants.DB.NAME).toString());
        }
        if(map.get(Constants.DB.CODE) != null && !map.get(Constants.DB.CODE).equals("")){
            queryWrapper.eq(Constants.DB.CODE,map.get(Constants.DB.CODE));
        }
        if(map.get(Constants.DB.STATUS) != null && !map.get(Constants.DB.STATUS).equals("")){
            queryWrapper.eq(Constants.DB.STATUS,map.get(Constants.DB.STATUS));
        }
        queryWrapper.orderByDesc(Constants.DB.CODE);
        IPage<Dictionary> result = MapperFactory.dictionaryMapper.selectPage(iPage, queryWrapper);
        return new PageResult<Dictionary>(result.getTotal(),result.getRecords());

    }

    public Result save(Dictionary dictionary) {
        MapperFactory.dictionaryMapper.insert(dictionary);
        return Result.SUCCESS();
    }

    public Result update(Dictionary dictionary) {
        Dictionary target = MapperFactory.dictionaryMapper.selectById(dictionary.getId());
        BeanUtils.copyProperties(dictionary,target);
        MapperFactory.dictionaryMapper.updateById(target);
        return Result.SUCCESS();
    }

    public List<Dictionary> search(Map<String, Object> map) {
        QueryWrapper<Dictionary> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Constants.DB.CODE,map.get(Constants.DB.CODE).toString());
        queryWrapper.eq(Constants.DB.STATUS,Constants.CharacterNumber.ONE);
        queryWrapper.orderByDesc(Constants.DB.CODE);
        return MapperFactory.dictionaryMapper.selectList(queryWrapper);
    }
}
